﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.IO.Ports;
using SerialPortHelperLib;
using XChip_Common;
using XChipTool.Enties;
using System.Configuration;
using BinAnalysisHelp;
using System.Threading;

namespace XChipTool
{
    public partial class XChip_Lite_Cfa : DevExpress.XtraEditors.XtraUserControl
    {
        public SerialPort sPortTemp;
        private bool isRead = false;
        private bool isWrite = false;
        private KeyEventArgs keyEnter = new KeyEventArgs(Keys.Enter);//用来手动触发文本框下发配置
        List<string> listfiltration = new List<string> { "slope", "scale_sig", "scale_enh" };
        //记录是否使用USB设备读写
        public bool IsUsbOpen = false;
        //记录是否使用I2C设备读写
        public bool m_open = false;
        private addressregisterManager aBll;
        private List<addressregister> XChipCfa;
        public parameter_exportManager Pe_dal { get; private set; }
        private string radiostr = string.Empty;

        public XChip_Lite_Cfa()
        {
            InitializeComponent();
        }
        public XChip_Lite_Cfa(SerialPort _sPortTemp, addressregisterManager _aBll)
        {
            sPortTemp = _sPortTemp;
            aBll = _aBll;
            XChipCfa = aBll.GetList(c => c.ChipType == ConfigurationManager.AppSettings["xc151_ChipType"] && (c.Classify == "CFA"));
            InitializeComponent();
        }
        private Control[] Controls_Find(string str)
        {
            //var t =   this.Controls.Find(type, true);
            List<Control> listc = new List<Control>();
            System.Reflection.FieldInfo[] fieldInfo = this.GetType().GetFields(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
            for (int i = 0; i < fieldInfo.Length; i++)
            {
                if (fieldInfo[i].Name.ToLower().Contains(str.ToLower()))
                {
                    listc.AddRange(this.Controls.Find(fieldInfo[i].Name, true));
                    //break;
                }
            }
            return listc.ToArray();
        }
        private void XChip_Reg_Cfa_Load(object sender, EventArgs e)
        {
            Task.Run(() => {
            this.Invoke((EventHandler)delegate {

              

                for (int i = 0; i < XChipCfa.Count; i++)
                {
                    
                    var type = AppHelper.NameTypeToString(XChipCfa[i].NameType);
                    //加上单选框的_en
                    //if (XChipCfa[i].ControlType == "1")
                    //{
                    //    type = XChipCfa[i].NameType;
                    //}
                    var col = Controls_Find(type);
                    

                    foreach (var item in col)
                    {
                        if (item is TextEdit)
                        {
                            //声明一个SuerToolTip
                            DevExpress.Utils.SuperToolTip graduationBatchSuperToolTip = new DevExpress.Utils.SuperToolTip();
                            //声明一个ToolTipTitleItem,保存标题
                            DevExpress.Utils.ToolTipTitleItem toolTipTitleItem = new DevExpress.Utils.ToolTipTitleItem();
                            String tooltips = "";
                            if (!string.IsNullOrEmpty(XChipCfa[i].Bit_Wide))
                            {
                                tooltips += $"位宽={XChipCfa[i].Bit_Wide}";
                            }
                            if (!string.IsNullOrEmpty(XChipCfa[i].Bit_Accuracy))
                            {
                                tooltips += $"|精度={XChipCfa[i].Bit_Accuracy}";
                            }
                            //设置标题文字
                            toolTipTitleItem.Text = tooltips;
                            //把标题添加到SuerToolTip
                            graduationBatchSuperToolTip.Items.Add(toolTipTitleItem);
                            //指定控件的SuperTip
                            ((TextEdit)item).SuperTip = graduationBatchSuperToolTip;
                            //正则判断
                            ((TextEdit)item).Properties.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.RegEx;
                            ((TextEdit)item).Properties.Mask.EditMask = BitsHelp.GetBitsToMask(XChipCfa[i].Bits, XChipCfa[i].Bit_Wide, XChipCfa.Where(c => c.NameType.ToLower().Contains(type) && c.ControlType == "0").Select(c => c.Bits).ToList());
                        }
                    }
                }
                });
            });
        }

        private long GetCFARegister(string nameType)
        {
            if (!sPortTemp.IsOpen && !IsUsbOpen && !m_open)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                return -1;
            }

            if (XChipCfa.Exists(c => c.NameType.ToLower() == nameType.ToLower()))
            {
                var model = XChipCfa.Find(c => c.NameType.ToLower() == nameType.ToLower());
                var Val = SerialSend.ReadRegister(Convert.ToUInt32(model.Address, 16), sPortTemp);
                if (model.ControlType.Contains("1"))
                {
                    return BitsHelp.GetBitsCheckedToBool(model.Bits, model.Hex, Val.ToString("X2"));
                }
                else
                {
                    return BitsHelp.GetBitsToUint(model.Bits, model.Hex, Val.ToString("X2"));
                }
            }
            else
            {
                DevExpress.XtraEditors.XtraMessageBox.Show($"未找到{nameType}"); return -1;
            }
        }
        private void SetCFARegister(addressregister model, ulong add, bool isCheck = true)
        {
            if (isRead) return;
            if (IsUsbOpen)
            {
               
                if (null != BinHelp.usbList)
                {
                    uint pVule = 0x0;
                    var isbool = false;
                    if (IntPtr.Size == 8)
                    {
                        isbool = XChipUSB.UsbRegisterRead64(BinHelp.CurrentSize, ref pVule, true);
                        SerialSend.Sendser("R:0x" + (BinHelp.CurrentSize).ToString("X2"), pVule.ToString("X2"));


                    }
                    else
                    {
                        isbool = XChipUSB.UsbRegisterRead86(BinHelp.CurrentSize, ref pVule, true);
                        SerialSend.Sendser("R:0x" + (BinHelp.CurrentSize).ToString("X2"), pVule.ToString("X2"));
                    }
                    var chang = (int)(pVule >> 16); // 使用右移16位操作来获取高16位  
                    var kuang = (int)(pVule & 0xFFFF); // 使用位与操作来获取低16位  


                    BinHelp.SstBinUsbUpdateData(ref BinHelp.BinList, model.Address, add.ToString("X"), chang, kuang);
                }
            }
            else if (m_open)
            {

            }
            else
            {
                if (!sPortTemp.IsOpen && !IsUsbOpen && !m_open)
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                    return;
                }
                if (isRead) return;
                
                if (null != BinHelp.lspList)
                { //编写Bin更新数据
                    var temp = SerialSend.ReadRegister(BinHelp.BootSettingIdx, sPortTemp);
                    BinHelp.SetBinUpdateData(ref BinHelp.BinList, model.Address, add.ToString("X"), (uint)temp);
                }

            }
            SerialSend.WriteRegister(Convert.ToUInt32(model.Address, 16), add, sPortTemp);
            //if (XChipCfa.Exists(c => c.NameType == nameType))
            //{
            //    SerialSend.WriteRegister(Convert.ToUInt32(XChipCfa.Where(c => c.NameType == nameType).First().Address, 16), add, sPortTemp);
            //}
        }


        private void fnr_en_CheckedChanged(object sender, EventArgs e)
        {
            //if (isRead) return;
            //var readVal = GetCFARegister("fnr_en");
            //SetCFARegister("fnr_en", (ulong)(fnr_en.Checked ? (readVal | 0x01) : (readVal & 0xfe)));
            //var readVal = SerialSend.ReadRegister(Convert.ToUInt32(XChipCfa.Find(c => c.NameType.ToLower() == $"fnr_en".ToLower()).Address, 16), sPortTemp);
            //var t = (ulong)(fnr_en.Checked ? (readVal | 0x01) : (readVal & 0xfe));
            //if (isRead) return;
            //if (XChipCfa.Exists(c => c.NameType.ToLower() == $"fnr_en".ToLower()))
            //{
            //    var model = XChipCfa.Find(c => c.NameType.ToLower() == $"fnr_en".ToLower());
            //    var Add = SerialSend.ReadRegister(Convert.ToUInt32(model.Address, 16), sPortTemp);
            //    var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), fnr_en.Checked);
            //    SetCFARegister(model, Val);
            //}
        }

        private void enh_en_CheckedChanged(object sender, EventArgs e)
        {
            //if (isRead) return;
            //var readVal = GetCFARegister("enh_en");
            //SetCFARegister("enh_en", (ulong)(enh_en.Checked ? (readVal | 0x01) : (readVal & 0xfe)));
            //var readVal = SerialSend.ReadRegister(Convert.ToUInt32(XChipCfa.Find(c => c.NameType.ToLower() == $"enh_en".ToLower()).Address, 16), sPortTemp);
            //var t = (ulong)(enh_en.Checked ? (readVal | 0x01) : (readVal & 0xfe));
            //if (isRead) return;
            //if (XChipCfa.Exists(c => c.NameType.ToLower() == $"enh_en".ToLower()))
            //{
            //    var model = XChipCfa.Find(c => c.NameType.ToLower() == $"enh_en".ToLower());
            //    var Add = SerialSend.ReadRegister(Convert.ToUInt32(model.Address, 16), sPortTemp);
            //    var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), enh_en.Checked);
            //    SetCFARegister(model, Val);
            //}
        }

        private void slope_k_KeyDown(object sender, KeyEventArgs e)
        {
            //if (e.KeyCode == Keys.Enter && !string.IsNullOrEmpty(slope_k.Text))
            //{
            //    //var nHigh = Convert.ToUInt32(slope_k.Text, 16);
            //    //SetCFARegister("slope_k", (ulong)nHigh);

            //    if (XChipCfa.Exists(c => c.NameType.ToLower() == $"slope_k".ToLower()))
            //    {
            //        var model = XChipCfa.Find(c => c.NameType.ToLower() == $"slope_k".ToLower());
            //        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, slope_k.Text);
            //        SetCFARegister(model, Val);
            //    }
            //}
        }

        private void slope_k_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            slope_k_KeyDown(sender, keyEnter);
        }

        private void slope_b_KeyDown(object sender, KeyEventArgs e)
        {
            //if (e.KeyCode == Keys.Enter && !string.IsNullOrEmpty(slope_b.Text))
            //{
            //    //var nHigh = Convert.ToUInt32(slope_b.Text, 16);
            //    //SetCFARegister("slope_b", (ulong)nHigh);

            //    if (XChipCfa.Exists(c => c.NameType.ToLower() == $"slope_b".ToLower()))
            //    {
            //        var model = XChipCfa.Find(c => c.NameType.ToLower() == $"slope_b".ToLower());
            //        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, slope_b.Text);
            //        SetCFARegister(model, Val);
            //    }
            //}
        }

        private void slope_b_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            slope_b_KeyDown(sender, keyEnter);
        }

        private void offset_k_KeyDown(object sender, KeyEventArgs e)
        {
            //if (e.KeyCode == Keys.Enter && !string.IsNullOrEmpty(offset_k.Text))
            //{
            //    //var nHigh = Convert.ToUInt32(offset_k.Text, 16);
            //    //SetCFARegister("offset_k", (ulong)nHigh);
            //    if (XChipCfa.Exists(c => c.NameType.ToLower() == $"offset_k".ToLower()))
            //    {
            //        var model = XChipCfa.Find(c => c.NameType.ToLower() == $"offset_k".ToLower());
            //        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, offset_k.Text);
            //        SetCFARegister(model, Val);
            //    }
            //}
        }

        private void offset_k_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            offset_k_KeyDown(sender, keyEnter);
        }

        private void offset_b_KeyDown(object sender, KeyEventArgs e)
        {
            //if (e.KeyCode == Keys.Enter && !string.IsNullOrEmpty(offset_b.Text))
            //{
            //    //var nHigh = Convert.ToUInt32(offset_b.Text, 16);
            //    //SetCFARegister("offset_b", (ulong)nHigh);
            //    if (XChipCfa.Exists(c => c.NameType.ToLower() == $"offset_b".ToLower()))
            //    {
            //        var model = XChipCfa.Find(c => c.NameType.ToLower() == $"offset_b".ToLower());
            //        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, offset_b.Text);
            //        SetCFARegister(model, Val);
            //    }
            //}
        }

        private void offset_b_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            offset_b_KeyDown(sender, keyEnter);
        }

        private void fnr_str_KeyDown(object sender, KeyEventArgs e)
        {
            //if (e.KeyCode == Keys.Enter && !string.IsNullOrEmpty(fnr_str.Text))
            //{
            //    //var nHigh = Convert.ToUInt32(fnr_str.Text, 16);
            //    //SetCFARegister("fnr_str", (ulong)nHigh);
            //    if (XChipCfa.Exists(c => c.NameType.ToLower() == $"fnr_str".ToLower()))
            //    {
            //        var model = XChipCfa.Find(c => c.NameType.ToLower() == $"fnr_str".ToLower());
            //        var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, fnr_str.Text);
            //        SetCFARegister(model, Val);
            //    }
            //}
        }

        private void fnr_str_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            fnr_str_KeyDown(sender, keyEnter);
        }

        private void scale_sig_list_0_KeyDown(object sender, KeyEventArgs e)
        {
            //if (isWrite) return;
            //var txtEdit = sender as DevExpress.XtraEditors.TextEdit;
            //if (string.IsNullOrEmpty(txtEdit.Text)) return;
            //SetCFARegister($"scale_sig_list[{txtEdit.Tag.ToString()}]", (ulong)Convert.ToInt32(txtEdit.Text, 16));

            if (isWrite) return;
            var txtEdit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtEdit.Text)) return;
            if (XChipCfa.Exists(c => c.NameType.ToLower() == txtEdit.Name.ToLower()))
            {
                var model = XChipCfa.Find(c => c.NameType.ToLower() == txtEdit.Name.ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
                SetCFARegister(model, Val);
            }

        }

        private void scale_sig_list_0_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            scale_sig_list_0_KeyDown(sender, keyEnter);
        }

        private void scale_enh_list_0_KeyDown(object sender, KeyEventArgs e)
        {
            //if (isWrite) return;
            //var txtEdit = sender as DevExpress.XtraEditors.TextEdit;
            //if (string.IsNullOrEmpty(txtEdit.Text)) return;
            //SetCFARegister($"scale_enh_list[{txtEdit.Tag.ToString()}]", (ulong)Convert.ToInt32(txtEdit.Text, 16));
            if (isWrite) return;
            var txtEdit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtEdit.Text)) return;
            if (XChipCfa.Exists(c => c.NameType.ToLower() == txtEdit.Name.ToLower()))
            {
                var model = XChipCfa.Find(c => c.NameType.ToLower() == txtEdit.Name.ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
                SetCFARegister(model, Val);
            }

        }

        private void scale_enh_list_0_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            scale_enh_list_0_KeyDown(sender, keyEnter);
        }

        private void scale_sbl_list_0_KeyDown(object sender, KeyEventArgs e)
        {
            //if (isWrite) return;
            //var txtEdit = sender as DevExpress.XtraEditors.TextEdit;
            //if (string.IsNullOrEmpty(txtEdit.Text)) return;
            //SetCFARegister($"scale_sbl_list[{txtEdit.Tag.ToString()}]", (ulong)Convert.ToInt32(txtEdit.Text, 16));
            if (isWrite) return;
            var txtEdit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtEdit.Text)) return;
            if (XChipCfa.Exists(c => c.NameType.ToLower() == txtEdit.Name.ToLower()))
            {
                var model = XChipCfa.Find(c => c.NameType.ToLower() == txtEdit.Name.ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
                SetCFARegister(model, Val);
            }

        }

        private void scale_sbl_list_0_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            scale_sbl_list_0_KeyDown(sender, keyEnter);
        }

        private void scale_sig_man_en_CheckedChanged(object sender, EventArgs e)
        {
            //if (isRead) return;
            //var readVal = GetCFARegister("scale_sig_man_en");
            //SetCFARegister("scale_sig_man_en", (ulong)(scale_sig_man_en.Checked ? (readVal | 0x01) : (readVal & 0xfe)));
            //var readVal = SerialSend.ReadRegister(Convert.ToUInt32(XChipCfa.Find(c => c.NameType.ToLower() == $"scale_sig_man_en".ToLower()).Address, 16), sPortTemp);
            //var t = (ulong)(scale_sig_man_en.Checked ? (readVal | 0x01) : (readVal & 0xfe));
            if (isRead) return;
            if (XChipCfa.Exists(c => c.NameType.ToLower() == $"scale_sig_man_en".ToLower()))
            {
                var model = XChipCfa.Find(c => c.NameType.ToLower() == $"scale_sig_man_en".ToLower());
                var Add = SerialSend.ReadRegister(Convert.ToUInt32(model.Address, 16), sPortTemp);
                var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), scale_sig_man_en.Checked);
                SetCFARegister(model, Val);
            }
            EnShowHide();

        }

        private void scale_enh_man_en_CheckedChanged(object sender, EventArgs e)
        {
            //if (isRead) return;
            //var readVal = GetCFARegister("scale_enh_man_en");
            //SetCFARegister("scale_enh_man_en", (ulong)(scale_enh_man_en.Checked ? (readVal | 0x01) : (readVal & 0xfe)));
            //var readVal = SerialSend.ReadRegister(Convert.ToUInt32(XChipCfa.Find(c => c.NameType.ToLower() == $"scale_enh_man_en".ToLower()).Address, 16), sPortTemp);
            //var t = (ulong)(scale_enh_man_en.Checked ? (readVal | 0x01) : (readVal & 0xfe));
            if (isRead) return;
            if (XChipCfa.Exists(c => c.NameType.ToLower() == $"scale_enh_man_en".ToLower()))
            {
                var model = XChipCfa.Find(c => c.NameType.ToLower() == $"scale_enh_man_en".ToLower());
                var Add = SerialSend.ReadRegister(Convert.ToUInt32(model.Address, 16), sPortTemp);
                var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), scale_enh_man_en.Checked);
                SetCFARegister(model, Val);
            }
            EnShowHide();
        }

        private void tunning_disp_en_CheckedChanged(object sender, EventArgs e)
        {
            //if (isRead) return;
            //var readVal = GetCFARegister("tunning_disp_en");
            //SetCFARegister("tunning_disp_en", (ulong)(tunning_disp_en.Checked ? (readVal | 0x01) : (readVal & 0xfe)));
            //var readVal = SerialSend.ReadRegister(Convert.ToUInt32(XChipCfa.Find(c => c.NameType.ToLower() == $"tunning_disp_en".ToLower()).Address, 16), sPortTemp);
            //var t = (ulong)(tunning_disp_en.Checked ? (readVal | 0x01) : (readVal & 0xfe));
            if (isRead) return;
            if (XChipCfa.Exists(c => c.NameType.ToLower() == $"tunning_disp_en".ToLower()))
            {
                var model = XChipCfa.Find(c => c.NameType.ToLower() == $"tunning_disp_en".ToLower());
                var Add = SerialSend.ReadRegister(Convert.ToUInt32(model.Address, 16), sPortTemp);
                var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), tunning_disp_en.Checked);
                SetCFARegister(model, Val);
            }
            EnShowHide();
        }

        private void scale_sig_man_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter && !string.IsNullOrEmpty(scale_sig_man.Text))
            {
                //var nHigh = Convert.ToUInt32(scale_sig_man.Text, 16);
                //SetCFARegister("scale_sig_man", (ulong)nHigh);
                if (XChipCfa.Exists(c => c.NameType.ToLower() == $"scale_sig_man".ToLower()))
                {
                    var model = XChipCfa.Find(c => c.NameType.ToLower() == $"scale_sig_man".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, scale_sig_man.Text);
                    SetCFARegister(model, Val);
                }
            }
        }

        private void scale_sig_man_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            scale_sig_man_KeyDown(sender, keyEnter);
        }

        private void scale_enh_man_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter && !string.IsNullOrEmpty(scale_enh_man.Text))
            {
                //var nHigh = Convert.ToUInt32(scale_enh_man.Text, 16);
                //SetCFARegister("scale_enh_man", (ulong)nHigh);
                if (XChipCfa.Exists(c => c.NameType.ToLower() == $"scale_enh_man".ToLower()))
                {
                    var model = XChipCfa.Find(c => c.NameType.ToLower() == $"scale_enh_man".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, scale_enh_man.Text);
                    SetCFARegister(model, Val);
                }
            }
        }

        private void scale_enh_man_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            scale_enh_man_KeyDown(sender, keyEnter);
        }

        private void tunning_disp_sel_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter && !string.IsNullOrEmpty(tunning_disp_sel.Text))
            {
                //var nHigh = Convert.ToUInt32(tunning_disp_sel.Text, 16);
                //SetCFARegister("tunning_disp_sel", (ulong)nHigh);
                if (XChipCfa.Exists(c => c.NameType.ToLower() == $"tunning_disp_sel".ToLower()))
                {
                    var model = XChipCfa.Find(c => c.NameType.ToLower() == $"tunning_disp_sel".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, tunning_disp_sel.Text);
                    if (Convert.ToUInt32(tunning_disp_sel.Text, 16) > Val)
                    {
                        tunning_disp_sel.Text = Val.ToString("X");
                    }
                    SetCFARegister(model, Val);
                }
            }
        }

        private void tunning_disp_sel_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            tunning_disp_sel_KeyDown(sender, keyEnter);
        }

        private void tunning_disp_scale_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter && !string.IsNullOrEmpty(tunning_disp_scale.Text))
            {
                //var nHigh = Convert.ToUInt32(tunning_disp_scale.Text, 16);
                //SetCFARegister("tunning_disp_scale", (ulong)nHigh);
                if (XChipCfa.Exists(c => c.NameType.ToLower() == $"tunning_disp_scale".ToLower()))
                {
                    var model = XChipCfa.Find(c => c.NameType.ToLower() == $"tunning_disp_scale".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, tunning_disp_scale.Text);
                    if (Convert.ToUInt32(tunning_disp_scale.Text, 16) > Val)
                    {
                        tunning_disp_scale.Text = Val.ToString("X");
                    }
                    SetCFARegister(model, Val);
                }
            }
        }

        private void tunning_disp_scale_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            tunning_disp_scale_KeyDown(sender, keyEnter);
        }

        /// <summary>
        /// 获取数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton5_Click(object sender, EventArgs e)
        {
            if (!sPortTemp.IsOpen && !IsUsbOpen && !m_open)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                return;
            }
            WaitBefore.Start("读取中", "正在加载中", 10);
            isRead = true;
            //string nameType = string.Empty;

            //List<string> NameList = new List<string>();
            //for (int i = 0; i < XChipCfa.Count; i++)
            //{

            //    var type = AppHelper.NameTypeToString(XChipCfa[i].NameType);
            //    //if (type.Contains("fnr"))
            //    //{

            //    //}
            //    if (NameList.Exists(c => c.ToLower().Contains(type)))
            //    {
            //        continue;
            //    }
            //    try
            //    {
            //        var col = Controls_Find(type);
            //        foreach (var item in col)
            //        {
            //            if (item is TextEdit)
            //            {
            //                //过滤掉指定寄存器
            //                if (listfiltration.Exists(c => c == col.ToString()))
            //                {
            //                    continue;
            //                }
            //                var nameList = XChipCfa.Where(c => c.NameType.ToLower().Contains(type)).ToList();
            //                long tempU = 0;
            //                foreach (var nitem in nameList)
            //                {
            //                    tempU += GetCFARegister(nitem.NameType);
            //                }
            //                item.Text = tempU.ToString("X");
            //            }
            //            else if (item is CheckEdit)
            //            {
            //                (item as CheckEdit).Checked = (GetCFARegister($"{type}_en") == 0);
            //            }
            //        }
            //        NameList.Add(type);

            //    }
            //    catch (Exception)
            //    {
            //        continue;
            //    }
            //}


            isRead = true;
            long nMask = GetCFARegister("Scene_Mode") & 0x03;
            if (nMask == 0)
            {
                rdo_scene.SelectedIndex = 0;
                radiostr = "_day";
            }
            else /*if (nMask == 1)*/
            {
                rdo_scene.SelectedIndex = 1;
                radiostr = "_night";
            }
            //else if (nMask == 2)
            //{
            //    AE_radiomode.SelectedIndex = 2;
            //}
            //Scene_Switch_En
            if ((GetCFARegister("nEffectSceneMode") == 0x12))
            {
                checkedListBoxControl1.Items[0].CheckState = CheckState.Checked;
                checkedListBoxControl1.Items[1].Enabled = true;
            }
            else
            {
                checkedListBoxControl1.Items[0].CheckState = CheckState.Unchecked;
                checkedListBoxControl1.Items[1].Enabled = false;
                rdo_scene.Enabled = false;
            }
            //Debug_En
            if ((GetCFARegister("nSwitchMode") & 0x02) == 0x00)
            {
                checkedListBoxControl1.Items[1].CheckState = CheckState.Checked;
                if (checkedListBoxControl1.Items[0].CheckState == CheckState.Checked)
                {
                    rdo_scene.Enabled = true;
                }
            }
            else
            {
                checkedListBoxControl1.Items[1].CheckState = CheckState.Unchecked;
                rdo_scene.Enabled = false;
            }
            isRead = false;


            List<string> NameList = new List<string>();

            for (int i = 0; i < XChipCfa.Count; i++)
            {
                if (XChipCfa[i].NameType.Contains("min_shp"))
                {

                }
                var type = AppHelper.NameTypeToString(XChipCfa[i].NameType);
                if (NameList.Exists(c => c.ToLower() == (type)))
                {
                    continue;
                }
                //加上单选框的_en
                if (XChipCfa[i].ControlType == "1")
                {
                    type = XChipCfa[i].NameType;
                }
                var col = Controls_Find(type);

                foreach (var item in col)
                {
                    if (item is TextEdit)
                    {
                        //过滤掉指定寄存器
                        if (listfiltration.Exists(c => c == col.ToString()))
                        {
                            continue;
                        }

                        var nList = XChipCfa.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.NameType.ToLower().Contains(radiostr) && c.ControlType == "0").ToList();
                        if (nList.Count == 0)
                        {
                            nList = XChipCfa.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.ControlType == "0").ToList();
                        }
                        if (nList.Count == 1)
                        {
                            var Val = SerialSend.ReadRegister(Convert.ToUInt32(nList[0].Address, 16), sPortTemp).ToString("X");
                            item.Text = BitsHelp.GetBitsToUint(nList[0].Bits, nList[0].Hex, Val).ToString("X");
                        }
                        else
                        {
                            string Val = string.Empty;
                            //这里默认为是有多个寄存器  一个文本框的情况进行处理
                            if (nList.Exists(c => c.NameType.ToLower().Contains("_h")))
                            {
                                Val += SerialSend.ReadRegister(Convert.ToUInt32(nList.Find(c => c.NameType.ToLower().Contains("_h")).Address, 16), sPortTemp).ToString("X2");
                            }
                            if (nList.Exists(c => c.NameType.ToLower().Contains("_m2")))
                            {
                                Val += SerialSend.ReadRegister(Convert.ToUInt32(nList.Find(c => c.NameType.ToLower().Contains("_m0")).Address, 16), sPortTemp).ToString("X2");
                            }
                            if (nList.Exists(c => c.NameType.ToLower().Contains("_m1")))
                            {
                                Val += SerialSend.ReadRegister(Convert.ToUInt32(nList.Find(c => c.NameType.ToLower().Contains("_m1")).Address, 16), sPortTemp).ToString("X2");
                            }
                            if (nList.Exists(c => c.NameType.ToLower().Contains("_m0")))
                            {
                                Val += SerialSend.ReadRegister(Convert.ToUInt32(nList.Find(c => c.NameType.ToLower().Contains("_m2")).Address, 16), sPortTemp).ToString("X2");
                            }
                            if (nList.Exists(c => c.NameType.ToLower().Contains("_l")))
                            {
                                if (nList.Exists(c => c.NameType.ToLower().Substring(c.NameType.Length - 2).Contains("_l")))
                                {
                                    Val += SerialSend.ReadRegister(Convert.ToUInt32(nList.Find(c => c.NameType.ToLower().Substring(c.NameType.Length - 2).Contains("_l")).Address, 16), sPortTemp).ToString("X2");
                                }
                                else
                                {
                                    Val += SerialSend.ReadRegister(Convert.ToUInt32(nList.Last(c => c.NameType.ToLower().Contains("_l")).Address, 16), sPortTemp).ToString("X2");
                                }
                            }

                            item.Text = Val;
                        }
                    }
                    else if (item is CheckEdit)
                    {
                        var nList = XChipCfa.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.ControlType == "1").ToList();
                        if (nList.Count == 1)
                        {
                            var Val = SerialSend.ReadRegister(Convert.ToUInt32(nList[0].Address, 16), sPortTemp).ToString("X");
                            (item as CheckEdit).Checked = BitsHelp.GetBitsCheckedToBool(nList[0].Bits, nList[0].Hex, Val) == 0;
                        }
                    }
                    NameList.Add(item.Name);

                }

                //NameList.Add(type);
            }
            EnShowHide();
            isRead = false;
            WaitBefore.Close();



        }

        public void Get_SlopeOffsetSigmaNr()
        {
            //slope.Text = GetCFARegister("slope").ToString("X2");
            //offset.Text = (GetCFARegister("offset_h") + GetCFARegister("offset_l")).ToString("X4");
            //scale_sig.Text = GetCFARegister("scale_sig").ToString("X2");
            //scale_enh.Text = GetCFARegister("scale_enh").ToString("X2");
            
        }

        private void simpleButton3_Click(object sender, EventArgs e)
        {
            Get_SlopeOffsetSigmaNr();
        }

        private void btn_SaveISPSetting_Click(object sender, EventArgs e)
        {
            if (!sPortTemp.IsOpen && !IsUsbOpen && !m_open)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                return;
            }

            SaveFileDialog sfd = new SaveFileDialog();
            //设置文件类型 
            sfd.Filter = "配置文件（*.txt）|*.txt";

            //设置默认文件类型显示顺序 
            sfd.FilterIndex = 1;

            //保存对话框是否记忆上次打开的目录 
            sfd.RestoreDirectory = true;
            sfd.FileName = "IQ_Setting_CFA_" + DateTime.Now.ToString("yyyyMMddHHmmss");
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                SerialSend.isDebug = false;
                StringBuilder sb = new StringBuilder();
                Pe_dal = new parameter_exportManager();
                if (null != Pe_dal)
                {
                    WaitBefore.Start("参数导出", "正在加载中", 60);
                    //var tempList = Pe_dal.GetList().OrderBy(c => c.SortNum);
                    var tempList = Pe_dal.GetList(c => c.Module == "CFA").OrderBy(c => c.SortNum).ToList();
                 
                    sb.Append("0xffff,0xfef1,\n");
                    sb.Append("\n");
                    sb.Append($"//{tempList.First().Module}\n");
                    foreach (var item in tempList)
                    {
                        try
                        {
                            sb.Append(string.IsNullOrEmpty(item.PreNote) ? "" : "\n" + item.PreNote + "\n");
                            sb.Append(string.IsNullOrEmpty(item.addr) ? "" : item.addr);
                            #region 判断是否需要用白天的数据
                            if (!string.IsNullOrEmpty(item.ReadAddr))
                            {
                                
                                sb.Append($",0x{SerialSend.ReadRegister((Convert.ToUInt32(item.ReadAddr.Trim(), 16)), sPortTemp).ToString("x2")},");
                                
                            }
                            #endregion
                            sb.Append(string.IsNullOrEmpty(item.RearNote) ? "" : item.RearNote = item.RearNote.Replace("\\n", "\n").Replace("\\r", "\r"));
                            sb.Append("\n");
                        }
                        catch (Exception ex)
                        {
                            WaitBefore.Close();
                            
                            DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message);
                            return;
                        }
                    }
                    System.IO.File.WriteAllText(sfd.FileName, sb.ToString());
                    WaitBefore.Close();
                    DevExpress.XtraEditors.XtraMessageBox.Show("参数导出完成");
                }
            }
            SerialSend.isDebug = true;
        }

        private void checkedListBoxControl1_ItemCheck(object sender, DevExpress.XtraEditors.Controls.ItemCheckEventArgs e)
        {
            if (isRead) return;

            //Scence Switch En 
            var nTemp1 = GetCFARegister("nEffectSceneMode");
            // Debug en
            var nTemp2 = GetCFARegister("nSwitchMode");
            if (checkedListBoxControl1.Items[0].CheckState == CheckState.Checked)//S勾选
            {
                //SetCmxRegister("nEffectSceneMode", (ulong)(nTemp1 | 0x04));
                SetCFARegister("nEffectSceneMode", 0x12);
                checkedListBoxControl1.Items[1].Enabled = true;
                if (checkedListBoxControl1.Items[1].CheckState == CheckState.Checked)//D勾选
                {
                    rdo_scene.Enabled = true;
                }
            }
            else  //S不勾选
            {
                //SetCmxRegister("nEffectSceneMode", (ulong)(nTemp1 & 0xfb));
                SetCFARegister("nEffectSceneMode", 0x00);
                checkedListBoxControl1.Items[1].Enabled = false;
                rdo_scene.Enabled = false;
            }


            if (checkedListBoxControl1.Items[1].CheckState == CheckState.Checked)//D勾选
            {
                //

                SetCFARegister("nSwitchMode", (ulong)(nTemp2 & 0xfd));
                if (checkedListBoxControl1.Items[0].CheckState == CheckState.Checked)//S勾选
                {
                    rdo_scene.Enabled = true;
                }
            }
            else//D不勾选
            { //

                SetCFARegister("nSwitchMode", (ulong)(nTemp2 | 0x02));
                rdo_scene.Enabled = false;
            }
        }

        private void rdo_scene_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (isRead) return;
            var aeradio = sender as DevExpress.XtraEditors.RadioGroup;

            if (aeradio.EditValue.ToString() == "1")
            {
                SetCFARegister("Scene_Mode", 0x00);
                radiostr = "_day";
            }
            else if (aeradio.EditValue.ToString() == "2")
            {
                SetCFARegister("Scene_Mode", 0x01);
                radiostr = "_night";
            }
            //else if (aeradio.EditValue.ToString() == "3")
            //{
            //    SetCFARegister("Scene_Mode", 0x02);
            //}

            Thread.Sleep(50);
            SerialSend.WriteRegister(0x80140a8f, 0x01, sPortTemp);

            simpleButton5_Click(null, null);
        }


        private void SetCFARegister(string nameType, ulong add)
        {
            if (IsUsbOpen)
            {
               

                if (null != BinHelp.usbList)
                {
                    uint pVule = 0x0;
                    var isbool = false;
                    if (IntPtr.Size == 8)
                    {
                        isbool = XChipUSB.UsbRegisterRead64(BinHelp.CurrentSize, ref pVule, true);
                        SerialSend.Sendser("R:0x" + (BinHelp.CurrentSize).ToString("X2"), pVule.ToString("X2"));


                    }
                    else
                    {
                        isbool = XChipUSB.UsbRegisterRead86(BinHelp.CurrentSize, ref pVule, true);
                        SerialSend.Sendser("R:0x" + (BinHelp.CurrentSize).ToString("X2"), pVule.ToString("X2"));
                    }
                    var chang = (int)(pVule >> 16); // 使用右移16位操作来获取高16位  
                    var kuang = (int)(pVule & 0xFFFF); // 使用位与操作来获取低16位  

                    BinHelp.SstBinUsbUpdateData(ref BinHelp.BinList, XChipCfa.Where(c => c.NameType.ToLower() == nameType.ToLower()).First().Address, add.ToString("X"), chang, kuang);
                }
            }
            else
            {
                if (!sPortTemp.IsOpen && !IsUsbOpen && !m_open)
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                    return;
                }
                if (isRead) return;
                if (XChipCfa.Where(c => c.NameType.ToLower() == nameType.ToLower()).Count() > 0)
                {
                    
                    if (null != BinHelp.lspList)
                    { //编写Bin更新数据
                        var temp = SerialSend.ReadRegister(BinHelp.BootSettingIdx, sPortTemp);
                        BinHelp.SetBinUpdateData(ref BinHelp.BinList, XChipCfa.Where(c => c.NameType.ToLower() == nameType.ToLower()).First().Address, add.ToString("X"), (uint)temp);
                    }
                }
            }
            if (XChipCfa.Where(c => c.NameType.ToLower() == nameType.ToLower()).Count() > 0)
            {
                SerialSend.WriteRegister(Convert.ToUInt32(XChipCfa.Where(c => c.NameType.ToLower() == nameType.ToLower()).First().Address, 16), add, sPortTemp);
            }

                



        }

        private void shp_en_CheckedChanged(object sender, EventArgs e)
        {
            if (isRead) return;
            var txt = sender as CheckEdit;
            if (XChipCfa.Exists(c => c.NameType.ToLower() == (txt.Name).ToLower()))
            {
                var model = XChipCfa.Find(c => c.NameType.ToLower() == (txt.Name).ToLower());
                var Add = SerialSend.ReadRegister(Convert.ToUInt32(model.Address, 16), sPortTemp);
                var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), txt.Checked);
                SetCFARegister(model, Val);
            }
        }

        private void CIP_10_en_CheckedChanged(object sender, EventArgs e)
        {
            if (isRead) return;
            var txt = sender as CheckEdit;
            if (XChipCfa.Exists(c => c.NameType.ToLower() == (txt.Name).ToLower()))
            {
                var model = XChipCfa.Find(c => c.NameType.ToLower() == (txt.Name).ToLower());
                var Add = SerialSend.ReadRegister(Convert.ToUInt32(model.Address, 16), sPortTemp);
                var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), txt.Checked);
                SetCFARegister(model, Val);
            }
            EnShowHide();
        }

        private void min_detail_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (isWrite) return;
                if (isRead) return; //判断是否在读，读的时候不进行写           
                var txt = sender as DevExpress.XtraEditors.TextEdit;
                if (string.IsNullOrEmpty(txt.Text)) return;
                if (XChipCfa.Exists(c => c.NameType.ToLower() == (txt.Name).ToLower()))
                {
                    var model = XChipCfa.Find(c => c.NameType.ToLower() == (txt.Name).ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetCFARegister(model, Val);
                }
            }
        }

        private void min_detail_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            min_detail_KeyDown(sender, keyEnter);
        }

        private void min_shp_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (isWrite) return;
                if (isRead) return; //判断是否在读，读的时候不进行写           
                var txt = sender as DevExpress.XtraEditors.TextEdit;
                if (string.IsNullOrEmpty(txt.Text)) return;
                if (XChipCfa.Exists(c => c.NameType.ToLower() == (txt.Name).ToLower()))
                {
                    var model = XChipCfa.Find(c => c.NameType.ToLower() == (txt.Name).ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetCFARegister(model, Val);
                }

                if (string.IsNullOrEmpty(txt.Text)) return;
                if (XChipCfa.Exists(c => c.NameType.ToLower() == (txt.Name + radiostr).ToLower()))
                {
                    var model = XChipCfa.Find(c => c.NameType.ToLower() == (txt.Name + radiostr).ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetCFARegister(model, Val);
                }

            }
        }

        private void min_shp_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            min_shp_KeyDown(sender, keyEnter);
        }
        private void EnShowHide()
        {
            scale_sig_man.Enabled = scale_sig_man_en.Checked;
            scale_enh_man.Enabled = scale_enh_man_en.Checked;
            tunning_disp_sel.Enabled = tunning_disp_en.Checked;
            tunning_disp_scale.Enabled = tunning_disp_en.Checked;

            cip_noise.Enabled = CIP_10_en.Checked;
            min_shp.Enabled = CIP_10_en.Checked;
            max_shp.Enabled = CIP_10_en.Checked;
            min_detail.Enabled = CIP_10_en.Checked;
            max_detail.Enabled = CIP_10_en.Checked;
            min_shp_gain.Enabled = CIP_10_en.Checked;
            max_shp_gain.Enabled = CIP_10_en.Checked;

            scale_sig_list0.Enabled = !scale_sig_man_en.Checked;
            scale_sig_list1.Enabled = !scale_sig_man_en.Checked;
            scale_sig_list2.Enabled = !scale_sig_man_en.Checked;
            scale_sig_list3.Enabled = !scale_sig_man_en.Checked;
            scale_sig_list4.Enabled = !scale_sig_man_en.Checked;
            scale_sig_list5.Enabled = !scale_sig_man_en.Checked;
            scale_sig_list6.Enabled = !scale_sig_man_en.Checked;
            scale_sig_list7.Enabled = !scale_sig_man_en.Checked;
            scale_sig_list8.Enabled = !scale_sig_man_en.Checked;

            scale_enh_list0.Enabled = !scale_enh_man_en.Checked;
            scale_enh_list1.Enabled = !scale_enh_man_en.Checked;
            scale_enh_list2.Enabled = !scale_enh_man_en.Checked;
            scale_enh_list3.Enabled = !scale_enh_man_en.Checked;
            scale_enh_list4.Enabled = !scale_enh_man_en.Checked;
            scale_enh_list5.Enabled = !scale_enh_man_en.Checked;
            scale_enh_list6.Enabled = !scale_enh_man_en.Checked;
            scale_enh_list7.Enabled = !scale_enh_man_en.Checked;
            scale_enh_list8.Enabled = !scale_enh_man_en.Checked;
        }
    }
}
